﻿using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using Core.Caching;
using Core.Helpers;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Organizations.Caching;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Organizations.Features.Commands.Update;

public class UpdateOrganizationCommand : ICacheInvalidatorRequest<Result<bool>>
{
    /// <summary>
    /// 唯一标识符
    /// </summary>
    [Required(ErrorMessage = "唯一标识是必填的")]
    public required Guid Id { get; set; }

    /// <summary>
    /// 组织机构名称
    /// </summary>
    [Required(ErrorMessage = "名称是必填的")]
    public required string Name { get; set; }
    /// <summary>
    /// 组织机构编码
    /// </summary>
    [Required(ErrorMessage = "编码是必填的")]
    public required string Code { get; set; }
    /// <summary>
    /// 父级组织机构Id
    /// </summary>
    public Guid? ParentId { get; set; }

    /// <summary>
    /// 设置排序
    /// </summary>
    public int? Sort { get; set; }

    /// <summary>
    /// 设置描述
    /// </summary>
    public string? Description { get; set; }

    /// <summary>
    /// 设置启用/禁用
    /// </summary>
    public bool? Enabled { get; set; }

    [JsonIgnore]
    public string CacheKey => OrganizationsCacheKey.GetAllCacheKey;

    [JsonIgnore]
    public IEnumerable<string>? Tags => OrganizationsCacheKey.Tags;
}

public class UpdateOrganizationCommandHandler(IIdentityDbContext dbContext) :
    IRequestHandler<UpdateOrganizationCommand, Result<bool>>
{
    public async Task<Result<bool>> Handle(UpdateOrganizationCommand request, CancellationToken cancellationToken)
    {
        var organization = await dbContext.Organizations
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);
        ExceptionHelper.ThrowIfNull(organization, "组织机构不存在");

        if (organization!.Name != request.Name)
        {
            var used = await dbContext.Organizations
                .AnyAsync(x => x.Name == request.Name, cancellationToken);
            ExceptionHelper.ThrowIfTrue(used, "组织名称已被占用");
            organization?.Rename(request.Name);
        }

        if (organization!.Code != request.Code)
        {
            if (!string.IsNullOrWhiteSpace(request.Code))
            {
                var used = await dbContext.Organizations
                    .AnyAsync(x => x.Code == request.Code && x.Id != request.Id, cancellationToken);

                ExceptionHelper.ThrowIfTrue(used, "组织编码已被占用");
            }
            organization.UpdateCode(request.Code);
        }

        // 更新父级（关键：防止循环依赖）
        if (organization!.ParentId != request.ParentId)
        {
            if (organization.ParentId != null && request.ParentId.HasValue)
            {
                var newParent = await dbContext.Organizations
                    .FirstOrDefaultAsync(x => x.Id == request.ParentId.Value, cancellationToken);

                ExceptionHelper.ThrowIfNull(newParent, "父级组织不存在");

                bool createsCycle = await CheckForCycleAsync(organization.Id, request.ParentId.Value, cancellationToken);
                ExceptionHelper.ThrowIfTrue(createsCycle, "不能将组织设置为其自身的子组织或后代组织，以避免循环依赖。");
            }

            organization.ChangeParent(request.ParentId);
        }

        organization!.Sort = request.Sort;
        organization!.Description = request.Description;
        organization!.Enabled = request.Enabled ?? true;

        dbContext.Organizations.Update(organization!);

        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;
        return await Result<bool>.SucceedAsync(result, result, ["修改失败"]);
    }

    private async Task<bool> CheckForCycleAsync(Guid nodeId, Guid potentialParentId, CancellationToken cancellationToken)
    {
        var currentId = potentialParentId;
        const int maxDepth = 100; // 防止无限循环（深度限制）
        int depth = 0;

        while (currentId != Guid.Empty && depth < maxDepth)
        {
            if (currentId == nodeId)
            {
                return true; // 发现闭环
            }

            var parent = await dbContext.Organizations
                .Where(o => o.Id == currentId)
                .Select(o => o.ParentId)
                .FirstOrDefaultAsync(cancellationToken);

            currentId = (Guid)parent; // 继续向上查找
            depth++;
        }

        return false; // 无环
    }
}
